﻿/********************/
/*  By Left Studio  */
/*     @Ho 229      */
/********************/

#include "my_texteditor.h"

#include <QUrl>
#include <QMenu>
#include <QAction>
#include <QMimeData>
#include <QFileInfo>
#include <QImageReader>
#include <QContextMenuEvent>
#include <QScrollBar>
#include <QDebug>
#include <QPoint>
#include <QPainter>

#if _MSC_VER >= 1600
    #pragma execution_character_set("utf-8")
#endif

My_TextEditor::My_TextEditor(QWidget *parent) :
    QTextEdit(parent),
    m_contextMenu(new QMenu(this))
{
    // 调整字体背景色
    QPalette palette = this->palette();
    palette.setColor(QPalette::Highlight,QColor(93,99,121));

    this->setPalette(palette);

	init();
}


void My_TextEditor::init()
{
	is_Hand = false;
	m_preVBarPos = 0;
	m_divVBarPos = 0;
	m_ptPress.setX(0);
	m_ptPress.setY(0);

	m_ptRelease.setX(0);
	m_ptRelease.setY(0);

	QScrollBar* vbar = verticalScrollBar();
	qDebug() << "page set =" << vbar->pageStep();
	connect(vbar, SIGNAL(valueChanged(int)), this, SLOT(slt_verticalValueChange(int)));
}


void My_TextEditor::slt_verticalValueChange(int value) {
	qDebug() << " Vertical value =" << value;
	m_divVBarPos = value - m_preVBarPos;	
	m_preVBarPos = value;
	qDebug() << " Vertical  div value =" << m_divVBarPos;
	m_transform.translate(0, m_divVBarPos);
}

bool My_TextEditor::canInsertFromMimeData(const QMimeData *source) const
{
    return source->hasImage() || source->hasUrls() ||
            QTextEdit::canInsertFromMimeData(source);
}

void My_TextEditor::insertFromMimeData(const QMimeData *source)
{
    if (source->hasImage())
    {
        static int i = 1;
        QUrl url(QString("dropped_image_%1").arg(i++));
        this->dropImage(url, qvariant_cast<QImage>(source->imageData()));
    }
    else if (source->hasUrls())
    {
        for(QUrl &url : source->urls())
        {
            QFileInfo info(url.toLocalFile());
            if (QImageReader::supportedImageFormats().contains(
                        info.suffix().toLower().toLatin1()))
                this->dropImage(url, QImage(info.filePath()));
            else
                emit openFile(url.toLocalFile());
        }
    }
    else
        QTextEdit::insertFromMimeData(source);
}

void My_TextEditor::contextMenuEvent(QContextMenuEvent *event)
{
    m_contextMenu->exec(event->globalPos());
}

void My_TextEditor::dropImage(const QUrl &url, const QImage &image)
{
    if (!image.isNull())
    {
        int width,height;
        width=image.width();
        height=image.height();

        m_ImageSizeDialog=new ImageSizeDialog();
        m_ImageSizeDialog->initImageSize(&width,&height);
        m_ImageSizeDialog->setAttribute(Qt::WA_DeleteOnClose);
        if(m_ImageSizeDialog->exec() == QDialog::Accepted)
        {
            QTextImageFormat ImageFormat;
            ImageFormat.setWidth(width);
            ImageFormat.setHeight(height);
            ImageFormat.setName(url.toString());

            // 将图片插入到QTextEdit
            this->document()->addResource(QTextDocument::ImageResource, url, image);
            this->textCursor().insertImage(ImageFormat);
        }
        m_ImageSizeDialog=nullptr;
    }
}


void My_TextEditor::mousePressEvent(QMouseEvent *e)
{
	QTextEdit::mousePressEvent(e);
	viewport()->setCursor(Qt::ArrowCursor);
	if (is_Hand){
		
		if (e->button() == Qt::LeftButton) {
			//QPoint m_ptPress = m_transform.inverted().map(e->pos());   //将鼠标点击的坐标转为当前document中的坐标
			m_ptPress = (e->pos());
			qDebug() << "m_ptpress =" << m_ptPress;
			repaint();
		}
	}
	e->accept();
}

void My_TextEditor::mouseMoveEvent(QMouseEvent *e)
{
	QTextEdit::mouseReleaseEvent(e);
	if (is_Hand) {
		if (e->button() == Qt::LeftButton) {
			//m_ptRelease = m_transform.inverted().map(e->pos());   //将鼠标点击的坐标转为当前document中的坐标
			//m_ptRelease = e->pos();
			m_ptRelease = e->pos();
			qDebug() << "m_ptpress =" << m_ptPress;
			//slt_addRect(m_ptPress, m_ptRelease);
			
			repaint();

			
		}
	}
	e->accept();
}

void My_TextEditor::mouseReleaseEvent(QMouseEvent *e)
{
	QTextEdit::mouseReleaseEvent(e);
	if (is_Hand) {
		if (e->button() == Qt::LeftButton) {
			//m_ptRelease = m_transform.inverted().map(e->pos());   //将鼠标点击的坐标转为当前document中的坐标
			m_ptRelease = e->pos();
			qDebug() << "m_ptpress =" << m_ptPress;
			//slt_addRect(m_ptPress, m_ptRelease);
			
			repaint();
		}
	}
	e->accept();
	is_Hand = false;
}

void My_TextEditor::paintEvent(QPaintEvent *e)
{
	QTextEdit::paintEvent(e);
	//QRect rtl = e->rect();
	

	QPainter painter(viewport());
	painter.drawRect(0, 0, width() / 2, height() / 2);
	QRect rect(m_ptPress, m_ptRelease);
	painter.drawRect(rect);
	//for (auto& itRect : m_rectVec){
	//	/*QPoint ptTL, ptBR;*/
	//	QPen pen = painter.pen();
	//	pen.setWidth(1);
	//	pen.setColor(Qt::red);
	//	pen.setStyle(Qt::SolidLine);
	//	painter.setPen(pen);

	//	painter.drawRect(*itRect);
	//}
	//painter.setWindow(rtl);
	//painter.fillRect(rtl, palette().background());
	//painter.setTransform(m_transform);
	//

	//
	//
	////
	//painter.save();
	
	//for (auto& itRect : m_rectVec){
	//	/*QPoint ptTL, ptBR;*/
	//	QPen pen = painter.pen();
	//	pen.setWidth(1);
	//	pen.setColor(Qt::red);
	//	pen.setStyle(Qt::SolidLine);
	//	painter.setPen(pen);

	//	painter.drawRect(*itRect);
	//}

	//painter.restore();
	//painter.end();

	//QTextEdit::paintEvent(e);
}


void My_TextEditor::slt_addRect(const QPoint& tlPt, const QPoint& brPt)
{
	QRect rect(QPoint(qMin(m_ptPress.x(), m_ptRelease.x()), qMin(m_ptPress.y(), m_ptRelease.y())),
		QPoint(qMax(m_ptPress.x(), m_ptRelease.x()), qMax(m_ptPress.y(), m_ptRelease.y())));
	m_rectVec.push_back(&rect);
}